<?php
namespace Service;

class ProductAgent extends Base
{

    public function getDatabase()
    {
        return $this->get(DATABASE_PRODUCTAGENT);
    }

    public function hasAgent($userId, $mainProduct, $mainProductSpec)
    {
        $database = $this->getDatabase();
        $data = [
            'dry_user' => $userId,
            'dry_main_product' => $mainProduct,
            'dry_main_product_spec' => $mainProductSpec
        ];
        return $database->getOneByFields($data);
    }

    public function getAgentList($userId, $mainProduct)
    {
        $database = $this->getDatabase();
        $data = [
            'dry_user' => $userId,
            'dry_main_product' => $mainProduct
        ];
        return $database->getMoreByFields($data);
    }

    public function addAgent($userId, $mainProduct, $mainProductSpec, $startTime, $endTime)
    {
        $now = getDateTime();
        $insert = [
            'dry_user' => $userId,
            'dry_main_product' => $mainProduct,
            'dry_main_product_spec' => $mainProductSpec,
            'dry_start_time' => $startTime,
            'dry_end_time' => $endTime,
            'dry_add_date' => $now['date'],
            'dry_add_time' => $now['date_time']
        ];
        $database = $this->getDatabase();
        return $database->insert($insert);
    }

    public function getCurrentAgent($userId, $mainProduct, $orderTime)
    {
        $database = $this->getDatabase();
        return $database->getCurrentAgent($userId, $mainProduct, $orderTime);
    }

    public function getDiscount($userId, $mainProduct)
    {
        $now = getDateTime();
        $discount = 0;
        $list = $this->getAgentList($userId, $mainProduct);
        if(empty($list)){
            return $discount;
        }
        foreach($list as $productAgent){
            $mainProductSpec = $productAgent->dry_main_product_spec;
            $bool1 = in_array($mainProductSpec, getProductAgentMainProductSpec());
            $bool2 = $productAgent->dry_start_time <= $now['date_time'];
            $bool3 = $productAgent->dry_end_time >= $now['date_time'];
            if($bool1 && $bool2 && $bool3){
                $temp = getProductAgentDiscount($mainProduct, $mainProductSpec);
                if($temp > $discount){
                    $discount = $temp;
                }
            }
        }
        return $discount;
    }

}